<?php

namespace app\api\controller;

use app\api\lib\Wechat;
use app\api\lib\SuPengJun;
use app\api\service\DynamicService;
use app\api\service\UserService;
use app\common\model\dynamic\DynamicLikeModel;
use app\common\model\dynamic\DynamicModel;
use app\common\model\NoticeModel;
use app\common\model\user\UserAddressModel;
use app\common\model\user\UserFollowModel;
use app\common\model\user\UserModel;
use app\common\model\user\UserPrivacyModel;
use dengje\jwt\facade\JWTAuth;
use EasyWeChat\Factory;
use think\Request;

class User extends Controller
{
    protected array $middleware = [
        'api' => ['except' => ['register', 'details', 'content']],
        'orCheck' => ['only' => ['details', 'content']]
    ];

    /**
     * 微信授权登录
     */
    public function register(Request $request)
    {
        $code = $request->post('code');
//        if (!$code) return error('授权失败', 500001);
//        $app = Factory::miniProgram(Wechat::config()['config']);
//        $response = $app->auth->session($code);
//        if (!isset($response['openid'])) return error('授权失败', 500001);
//        $condition[] = ['wx_openid', '=', $response['openid']];
//        $condition[] = ['status', '=', 1];
        $condition[] = ['id', '=', 2];
        $userInfo = UserModel::where($condition)->field(UserService::user_find())->find();


        if (!$userInfo) {
            $model = [
                'name' => '用户' . SuPengJun::generateRandomCode(),
                'avatar' => request()->scheme() . '://' . request()->host() . '/avatar.png',
                'wx_openid' => $response['openid'],
                'gender' => 2,
                'create_time' => time()
            ];
            $model = SuPengJun::ipStr($model, $request->ip());
            (new UserModel())->insert($model);
            $userInfo = UserModel::where($condition)->field(UserService::user_find())->find();
            if (!UserPrivacyModel::where('user_id', $userInfo['id'])->value('id')) {
                (new UserPrivacyModel())->insert(['user_id' => $userInfo['id'], 'create_time' => time()]);
            }
            event('UserRegister', ['uid' => $userInfo['id']]);
        }
        $userInfo = UserService::user_other($userInfo, 0);
        $data['info'] = $userInfo;
        $data['token'] = JWTAuth::builder(['uid' => $userInfo['id']]);
        return success('success', $data);
    }

    public function refresh_info(Request $request)
    {
        $uid = $request->uid;
        $userInfo = UserModel::where('id', $uid)->field(UserService::user_find())->find();
        $userInfo = UserService::user_other($userInfo, 0);
        $data['info'] = $userInfo;
        $data['token'] = JWTAuth::builder(['uid' => $userInfo['id']]);

        return success('success', $data);
    }

    /**
     * 编辑用户信息
     * @param array $type 操作类型：1=修改昵称，2=修改简介，3=修改头像，0=修改性别、修改年龄
     * @param array $name 新昵称（type=1时必填）
     * @param array $intro 新简介（type=2时必填）
     * @param array $avatar 新头像（type=3时必填）
     * @param array $gender 性别（type=0时有效）
     * @param array $age 年龄（type=0时有效）
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function edit_info(Request $request)
    {
        $uid = $request->uid;
        $type = $request->post('type', 0);
        $model = [];
        if ($type == 1) {
            $isEvent = UserPrivacyModel::where('user_id', $uid)->update(['name' => $request->post('name'), 'examine' => 1]);
            if ($isEvent) event('UserAudit', ['uid' => $uid, 'type' => $type]);
            return success('昵称修改成功，审核通过后生效！');
        } else if ($type == 2) {
            $isEvent = UserPrivacyModel::where('user_id', $uid)->update(['intro' => $request->post('intro'), 'examine' => 1]);
            if ($isEvent) event('UserAudit', ['uid' => $uid, 'type' => $type]);
            return success('简介修改成功，审核通过后生效！');
        } else if ($type == 3) {
            $isEvent = UserPrivacyModel::where('user_id', $uid)->update(['avatar' => $request->post('avatar'), 'examine' => 1]);
            if ($isEvent) event('UserAudit', ['uid' => $uid, 'type' => $type]);
            event('UserAudit', ['uid' => $uid, 'type' => $type]);
            return success('头像修改成功，审核通过后生效！');
        }
        $model['gender'] = $request->post('gender');
        $model['age'] = $request->post('age');
        $model['update_time'] = time();
        UserModel::where('id', $uid)->update($model);
        return success('修改成功 🎉');
    }

    /**
     * 换绑手机号码（获取微信手机号）
     * @param array $code code
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function bind_mobile(Request $request)
    {
        $uid = $request->uid;
        $code = $request->post('code');
        if (!$code) return error('授权失败', 500001);
        $app = Factory::miniProgram(Wechat::config()['config']);
        $response = $app->phone_number->getUserPhoneNumber($code);
//        $response['errmsg'] = 'ok';
//        $response['phone_info']['phoneNumber'] = '18049022071';
        if ($response['errmsg'] == 'ok') {
            $model['update_time'] = time();
            $model['mobile'] = $response['phone_info']['phoneNumber'];
            UserModel::where('id', $uid)->update($model);
            $data = UserModel::where('id', $uid)->field(UserService::user_find())->find();
            $data = UserService::user_other($data, 0);
            return success('操作成功 🎉', $data);
        } else {
            return error('授权失败', 500001);
        }
    }

    /**
     * 刷新IP地址
     */
    public function refresh_ip(Request $request)
    {
        $uid = $request->uid;
        $model = SuPengJun::ipStr([], $request->ip());
        UserModel::where('id', $uid)->update($model);
        $data = UserModel::where('id', $uid)->field(UserService::user_find())->find();
        $data = UserService::user_other($data, 0);
        return success('刷新成功 🎉', $data);
    }

    /**
     * 方法名
     * @param array $param 参数类型参数名参数作用
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function privacy(Request $request)
    {
        $uid = $request->uid;
        $like = $request->post('like', 0);
        $search = $request->post('search', 0);
        $follow = $request->post('follow', 0);
        UserPrivacyModel::where('user_id', $uid)->update(['like' => $like, 'search' => $search, 'follow' => $follow]);
        return success('修改成功 🎉');
    }

    /**
     * 查看用户详情
     * @param array $userId 用户ID
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function details(Request $request)
    {
        $uid = $request->uid;
        $userId = $request->get('user_id', 0);
        $data = UserModel::where('id', $userId)->field(UserService::user_find())->find();
        if (!$data) return error('用户状态异常或不存在！', 500101);
        $data = UserService::user_other($data, $uid, $userId);
        return success('success', $data);
    }

    /**
     * 我的-动态列表
     * @param array $type 类型:0=笔记,1=点赞,2=草稿
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function dynamic(Request $request)
    {
        $uid = $request->uid;
        $type = $request->get('type', 0);
        $condition[] = ['user_id', '=', $uid];
        if ($type == 1) {
            $ids = DynamicLikeModel::where($condition)->order('id', 'desc')->column('dynamic_id');
            $idsOrdered = implode(',', $ids);
            if (count($ids)) {
                $data = DynamicModel::where('status', 2)
                    ->whereIn('id', $ids)
                    ->orderRaw("FIELD(id, $idsOrdered)")
                    ->field(DynamicService::dynamic_find())
                    ->paginate(8);
                if ($data) $data = DynamicService::dynamic_map($data);
            } else {
                $data['data'] = [];
            }
        } else {
            if ($type == 0) $condition[] = ['status', 'in', [1, 2, 3, 4]];
            if ($type == 2) $condition[] = ['status', '=', 0];
            $data = DynamicModel::where($condition)
                ->order('id', 'desc')
                ->field(DynamicService::dynamic_find())
                ->paginate(8);
            if ($data) $data = DynamicService::dynamic_map($data);
        }
        return success('success', $data);
    }

    /**
     * 获取用户发布的动态列表
     * @param array $type 类型:0=用户发布,1=用户点赞
     * @param array $userId 用户ID
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function content(Request $request)
    {
        $uid = $request->uid;
        $type = $request->get('type', 0);
        $userId = $request->get('user_id', 0);
        $condition[] = ['status', 'in', [2, 3]];
        if ($type == 0) {
            $condition[] = ['user_id', '=', $userId];
            $data = DynamicModel::where($condition)
                ->order('id', 'desc')
                ->field(DynamicService::dynamic_find())
                ->paginate(8);
            if ($data) $data = DynamicService::dynamic_map($data, $uid, 1);
        } else if ($type == 1) {
            $ids = DynamicLikeModel::where('user_id', $userId)->order('id', 'desc')->column('dynamic_id');
            $idsOrdered = implode(',', $ids);
            if (count($ids)) {
                $condition[] = ['id', 'in', $ids];
                $data = DynamicModel::where($condition)
                    ->orderRaw("FIELD(id, $idsOrdered)")
                    ->field(DynamicService::dynamic_find())
                    ->paginate(8);
                if ($data) $data = DynamicService::dynamic_map($data, $uid, 1);
            } else {
                $data['data'] = [];
            }
        }
        return success('success', $data);
    }

    /**
     * 方法名
     * @param array $param 参数类型参数名参数作用
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function follow(Request $request)
    {
        $uid = $request->uid;
        $userId = $request->post('user_id');
        $isFollow = $request->post('is_follow');
        if ($userId == $uid) return error('您不能关注您自己！');
        if ($isFollow) {
            UserFollowModel::where('user_id', $uid)
                ->where('follow_id', $userId)
                ->delete();
            return success('已取消关注！');
        } else {
            (new UserFollowModel)->insert([
                'user_id' => $uid,
                'follow_id' => $userId,
                'create_time' => time()
            ]);
            $userName = UserModel::where('id', $uid)->value('name');
            $avatarUrl = '/pages/user/details?id=' . $uid;
            $content = '<div style="margin-top: 8px;display: flex;">
            <div style="padding:0 12px;height: 40px;line-height: 40px;text-align: center;border-radius: 4px;background: #f5f5f5;
            font-weight: bold;font-size: 12px;">👉 查看"' . $userName . '"的名片</div></div>';
            (new NoticeModel())->send($userId, '开始关注你了', $content, $uid, $avatarUrl, $avatarUrl);
            return success('关注成功 🎉🎉');
        }
    }

    /**
     * 关注列表
     * @param array $type 类型:0=我关注的,1=我的粉丝
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function follow_list(Request $request)
    {
        $uid = $request->uid;
        $type = $request->get('type', 0);
        $userId = $request->get('user_id', 0);
        if ($userId) $uid = $userId;
        if ($type == 0) {
            $data = UserFollowModel::where('user_id', $uid)
                ->order('id', 'desc')
                ->field('id,follow_id')
                ->paginate(24)->toArray();
            foreach ($data['data'] as $k => $v) {
                $data['data'][$k]['user'] = UserModel::where('id', $v['follow_id'])->field('id,name,avatar,intro')->find();
                $data['data'][$k]['is_follow'] = UserFollowModel::where('user_id', $v['follow_id'])
                    ->where('follow_id', $uid)->value('id') > 0;
            }
        } else {
            $data = UserFollowModel::where('follow_id', $uid)
                ->order('id', 'desc')
                ->field('id,user_id')
                ->paginate(24)->toArray();
            foreach ($data['data'] as $k => $v) {
                $data['data'][$k]['user'] = UserModel::where('id', $v['user_id'])->field('id,name,avatar,intro')->find();
                $data['data'][$k]['is_follow'] = UserFollowModel::where('user_id', $uid)
                    ->where('follow_id', $v['user_id'])->value('id') > 0;
            }
        }
        return success('success', $data);
    }

    /**
     * 收货地址列表
     * @param array $param 参数类型参数名参数作用
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function address_list(Request $request)
    {
        $uid = $request->uid;
        $data = UserAddressModel::where('user_id', $uid)->where('status', 1)
            ->order(['default' => 'desc', 'id' => 'desc'])
            ->field('id,name,mobile,province,city,county,detailed,default')
            ->select();
        return success('success', $data);
    }

    /**
     * 新建收货地址
     * @param array $param 参数类型参数名参数作用
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function save_address(Request $request)
    {
        $uid = $request->uid;
        $param = $request->post();
        $param['user_id'] = $uid;
        if ($param['type'] == 1 && $param['id'] <= 0) {
            if ($param['default'] == 1) UserAddressModel::where('user_id', $uid)->where('id', '<>', $param['id'])->update(['default' => 0]);
            $param['create_time'] = time();
            unset($param["type"]);
            (new UserAddressModel)->insert($param);
        } else if ($param['type'] == 1 && $param['id'] > 0) {
            if ($param['default'] == 1) UserAddressModel::where('user_id', $uid)->where('id', '<>', $param['id'])->update(['default' => 0]);
            $param['update_time'] = time();
            unset($param["type"]);
            UserAddressModel::where('id', $param['id'])->update($param);
        } else if ($param['type'] == 2) {
            UserAddressModel::where('user_id', $uid)->where('id', $param['id'])->delete();
        } else if ($param['type'] == 3) {
            UserAddressModel::where('user_id', $uid)->update(['default' => 0]);
            UserAddressModel::where('user_id', $uid)->where('id', $param['id'])->update(['default' => 1]);
        }
        return success('操作成功 🎉🎉');
    }

    /**
     * 获取默认地址
     * @param array $id 地址ID
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function address_info(Request $request)
    {
        $uid = $request->uid;
        $id = $request->get('id');
        $condition[] = ['status', '=', 1];
        $condition[] = ['user_id', '=', $uid];
        if ($id > 0) $condition[] = ['id', '=', $id];
        $data = UserAddressModel::where($condition)
            ->order(['default' => 'desc', 'id' => 'desc'])
            ->field('id,name,mobile,province,city,county,detailed')
            ->find();
        return success('成功', $data);
    }

    /**
     * 注销账号
     */
    public function logout(Request $request)
    {
        $uid = $request->uid;
        UserModel::where('id', $uid)->update([
            'avatar' => request()->scheme() . '://' . request()->host() . '/avatar.png',
            'name' => '账号已经注销',
            'status' => 8,
            'update_time' => time()
        ]);
        DynamicModel::where('user_id', $uid)->update(['status' => 3]);
        return success('已成功为您注销账号！');
    }
}
